package com.kk.springboot_001.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.kk.springboot_001.pojo.dto.Fruit;
import com.kk.springboot_001.service.FruitService;
import com.kk.springboot_001.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;

@RestController
@RequestMapping("/fruits")
public class FruitController {

    @Autowired
    private FruitService fruitService;
    @Autowired
    private UserService userService;

    /**
     * 获取水果列表
     * @param page
     * @param size
     * @param authentication
     * @return
     */
    @GetMapping
    public IPage<Fruit> getFruits(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size,
                                  Authentication authentication) {
        String userName = authentication.getName();
        // 根据用户名获取 userId
        Integer userId = userService.getUserIdByUserName(userName);
        return fruitService.getFruitsByUserIdWithPagination(userId, page, size);
    }


    /**
     * 添加水果
     * @param fruit
     * @param authentication
     * @return
     */
    @PostMapping
    public ResponseEntity<Map<String, String>> addFruit(@RequestBody Fruit fruit, Authentication authentication) {
        String userName = authentication.getName();
        Integer userId = userService.getUserIdByUserName(userName);
        fruit.setUserId(userId);

        try {
            fruitService.addFruit(fruit);
            // 成功后返回一个包含成功信息的 JSON 响应
            return ResponseEntity.ok(Collections.singletonMap("message", "水果添加成功！"));
        } catch (RuntimeException e) {
            // 失败后返回一个包含错误信息的 JSON 响应和 400 Bad Request 状态码
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("message", e.getMessage()));
        }
    }



}